<template>
  <div>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @change="getTableTitle"></Search>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleAdd" :disabled="butStatus.add" type="success"> 创建 </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="handleUpdate" :disabled="butStatus.update"> 修改 </el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDelete" :disabled="butStatus.rm" type="danger"> 删除 </el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <template>
      <el-table v-loading="listLoading"
                :data="tableData"
                style="width: 100%"
                border
                @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column v-for="item in tableTile"
                         :prop="item.key"
                         :label="item.name">
        </el-table-column>
        <el-table-column label="状态">
          <template scope="scope">
            {{scope.row.status | todataauthsta}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button type="primary" size='mini'
                       :disabled="scope.row.status!=2"
                       @click="reSubmit(scope.row)">重新提交
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParm.currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageParm.page_size"
        :total="pageParm.count"
        layout="total, sizes, prev, pager, next, jumper"
        style="float:right">
      </el-pagination>
    </el-col>
    <!--编辑界面-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible" size="tiny" :close="resetForm">
      <el-form label-position="right" :model="form" :rules="rules" ref="form" :label-width="formLabelWidth"
               class="form-submit">
        <el-form-item v-if="editinpStatus.policy_type" label="策略类型" prop="policy_type">
          <el-radio-group v-model="form.policy_type" :disabled="disabled" @change="cgHiveType">
            <el-radio label="普通策略" value="普通策略"></el-radio>
            <el-radio label="模糊化策略" value="模糊化策略"></el-radio>
            <el-radio label="行过滤策略" value="行过滤策略"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="editinpStatus.priv_policy_id" label="ID" prop="priv_policy_id">
          <el-input v-model="form.priv_policy_id" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.policy_name" label="策略名" prop="policy_name">
          <el-input v-model="form.policy_name"
                    auto-complete="off"
                    :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.hdfs_dirs" label="作用路径" prop="hdfs_dirs">
          <el-input v-model="form.hdfs_dirs" :disabled="disabled" v-if="disabled"></el-input>
          <UploadPath v-model="form.hdfs_dirs" ref="mUpload" uploadType="2" v-else></UploadPath>
        </el-form-item>
        <el-form-item v-if="editinpStatus.queue" label="队列" prop="queue">
          <el-select v-model="form.queue" :disabled="disabled" placeholder="请选择">
            <el-option
              v-for="item in queueOpts"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editinpStatus.topic" label="Topic" prop="topic">
          <el-select v-model="form.topic" multiple :disabled="disabled" placeholder="请选择Topic">
            <el-option
              v-for="item in topicList"
              :label="item.kafka_topic_name"
              :value="item.kafka_topic_name">
            </el-option>
          </el-select>
          <!--<el-input v-model="form.topic" :disabled="disabled"></el-input>-->
        </el-form-item>
        <el-form-item v-if="editinpStatus.database" label="数据库" prop="database">
          <el-select v-model="form.database"
                     filterable
                     multiple
                     placeholder="请选择"
                     :disabled="disabled"
                     @change="changeDb('database')">
            <el-option v-for="item in databaseNameopts"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editinpStatus.udfSel" label="类型" prop="udfSel">
          <el-select v-model="form.udfSel" placeholder="请选择" @change="cgUdfSel" :disabled="disabled">
            <el-option key="udf" label="udf" value="udf"></el-option>
            <el-option key="table" label="table" value="table"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item v-if="editinpStatus.udf" label="udf" prop="udf">
          <el-input v-model="form.udf" :disabled="disabled"></el-input>
        </el-form-item>


        <el-form-item
          v-if="editinpStatus.hiveTables"
          label="作用表"
          prop="hiveTables"
          @change="changeDb('hiveTables')">
          <el-select v-model="form.hiveTables"
                     filterable
                     multiple
                     placeholder="请选择作用表"
                     :disabled="disabled">
            <el-option label="*" value="*"></el-option>
            <el-option
              v-for="item in hiveTableNameopts"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editinpStatus.hbaseTables" label="作用表" prop="hbaseTables">
          <el-select
            v-model="form.hbaseTables"
            filterable
            multiple
            allow-create
            placeholder="请选择"
            :disabled="disabled"
            @change="changeDb('hbaseTables')">
            <el-option
              v-for="item in hbaseTableNameopts"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editinpStatus.rule" label="模糊化规则" prop="rule">
          <el-select v-model="form.rule" @change="cgFRule" filterable placeholder="请选择">
            <el-option
              v-for="item in ruleOpts"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-input v-if="editinpStatus.ruleCode" style="margin-top:10px"
                    v-model="form.ruleCode"></el-input>
        </el-form-item>
        <!--列族在Ranger中必须填，需要输入	，20170309 增加，需后期确认-->
        <el-form-item v-if="editinpStatus.column_family" label="作用列族" prop="column_family">
          <el-input v-model="form.column_family" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.columns" label="作用列" prop="columns">
          <el-input v-model="form.columns" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.filter_expr" label="过滤表达式" prop="filter_expr">
          <el-input v-model="form.filter_expr" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.enabled" label="是否启用" prop="enabled">
          <el-switch
            v-model="form.enabled"
            on-color="#13ce66"
            off-color="#ff4949" disabled>
          </el-switch>
        </el-form-item>
        <el-form-item v-if="editinpStatus.isrecursion" label="递归" prop="isrecursion">
          <el-switch
            v-model="form.isrecursion"
            on-color="#13ce66"
            off-color="#ff4949" disabled>
          </el-switch>
        </el-form-item>
        <el-form-item v-if="editinpStatus.permissions" label="权限" prop="permissions">
          <el-select v-model="form.permissions" multiple placeholder="请选择" size="large">
            <el-option
              v-for="item in options"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editinpStatus.policy_desc" label="描述" prop="policy_desc">
          <el-input v-model="form.policy_desc"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import util from '../../common/util'
  import Search from '../../components/Search.vue'
  import UploadPath from '../../components/UploadPath.vue'
  import dao from '../../common/dao'
  import NProgress from 'nprogress'

  export default {
    components: {Search, UploadPath},
    props: {
      type: {
        type: String,
        default: 'hdfs5'
      },
      privdatas: {}
    },
    data () {
      return {
        rules: {
          policy_name: [
            {required: true, message: '请输入策略名称', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'},
            {validator: this.validatePolicyName, trigger: 'blur'}
          ],
          hdfs_dirs: [
            {required: true, message: '请输入路径!', trigger: 'blur'},
            {validator: util.validateFileName, trigger: 'blur'},
          ],
          queue: [{required: true, message: '请选择队列!', trigger: 'blur'}],
          database: [{type: "array", required: true, message: '请选择数据库!', trigger: 'blur'}],
          hiveTables: [{type: "array", required: true, message: '请选择作用表!', trigger: 'blur'}],
          hbaseTables: [{type: "array", required: true, message: '请选择作用表!', trigger: 'blur'}],
          columns: [
            {required: true, message: '请输入作用列!', trigger: 'blur'},
            //{validator: util.validateString, trigger: 'blur'}
          ],
          udf: [
            {required: true, message: '请输入udf!', trigger: 'blur'},
          ],
          column_family: [
            {required: true, message: '请输入作用列族!', trigger: 'blur'},
            //{validator: util.validateString, trigger: 'blur'}
          ],
          topic: [{type: "array", required: true, message: '请选择topic!', trigger: 'change'}],
          permissions: [{type: 'array', required: true, message: '请选择权限！', trigger: 'blur'},],
          rule: [{required: true, message: '请选择模糊化规则!', trigger: 'change'}],
          filter_expr: [
            {required: true, message: '请输入过滤表达式!', trigger: 'blur'},
            {validator: util.validateChinese, trigger: 'blur'}
          ],
        },
        formTitle: '修改',
        formLabelWidth: "100px",
        ruleOpts: [{
          label: 'Redact',
          value: 'Redact'
        }, {
          label: 'Partial mask: show last 4',
          value: 'Partial mask: show last 4'
        }, {
          label: 'Partial mask: show first 4',
          value: 'Partial mask: show first 4'
        }, {
          label: 'Hash',
          value: 'Hash'
        }, {
          label: 'Nullify',
          value: 'Nullify'
        }, {
          label: 'Unmasked (retain original value)',
          value: 'Unmasked (retain original value)'
        }, {
          label: 'Date: show only year',
          value: 'Date: show only year'
        }, {
          label: 'Custom',//Custom
          value: 'Custom'
        },],
        options: [],
        queueOpts: [],
        hiveTableNameopts: [],
        hbaseTableNameopts: [],
        databaseNameopts: [],
        disabled: false,
        btnEditText: "保存",
        editinpStatus: {
          udfSel: true,
          usf: false,
          priv_policy_id: false,
          policy_type: true,
          policy_name: true,
          hdfs_dirs: true,
          queue: true,
          topic: true,
          ip: true,
          hiveTables: true,
          hbaseTables: true,
          database: true,
          rule: true,
          ruleCode: false,
          column_family: true,
          columns: true,
          filter_expr: true,
          include: true,
          enabled: true, //是否启用
          isaudit: true,
          isrecursion: true,
          permissions: true,
          policy_desc: true,
        },
        dialogFormVisible: false,
        form: {},
        formInline: {
          allOpts: [{
            key: 'policy_name',
            label: '策略名',
            type: '',
            val: ''
          }],
          cOpts: [{
            key: 'policy_name',
            label: '策略名',
            type: '',
            val: ''
          }]
        },
        butStatus: {
          update: true,
          add: true,
          rm: true
        },
        ptype: this.type,
        tableTile: [],
        tableData: [],
        pageParm: {
          "count": 0, //总条数
          "page_size": 20, //每页条数
          "page_count": 0, //总页数
          "currentPage": 1 //当前页数
        },
        zhHelpTips: "",
        isSuccess: "0",
        addFun: '',
        updateFun: '',
        deleteFun: '',
      }
    },
    watch: {
      privdatas(n, o){
        this.form.role_id = this.privdatas.role_id;
        this.form.tenant_id = this.privdatas.tenant_id;
        if (this.type == 'hbase') {
          this.getHabseTableList();
        } else if (this.type == 'yarn') {
          this.getQueueOpts()
        } else if (this.type == 'hive') {
          this.getHiveTableList()
        }
        this.getTableTitle();
        this.butStatus.add = false;
      },
    },
    methods: {
      getHiveTypeatt (val) {
        let arrT = [];
        if (val == '普通策略') {
          arrT = ['policy_type', 'policy_name', 'database', "enabled", 'udfSel', 'udf', 'hiveTables', 'columns', 'include', 'isaudit', 'policy_desc', 'permissions']
        }
        else if (val == '模糊化策略') {
          arrT = ['policy_type', 'policy_name', 'database', "enabled", 'hiveTables', 'columns', 'include', 'isaudit', 'policy_desc', 'rule', 'permissions']
        }
        else if (val == '行过滤策略') {
          arrT = ['policy_type', 'policy_name', 'database', "enabled", 'hiveTables', 'isaudit', 'policy_desc', 'filter_expr', 'permissions']
        }
        return arrT
      },
      cgHiveType (val) {

        if (val == '普通策略') {
          this.updateOptions();
        }
        else if (val == '模糊化策略') {
          this.options = [{
            label: 'select',
            value: 'select'
          }];
        }
        else if (val == '行过滤策略') {
          this.options = [{
            label: 'select',
            value: 'select'
          }];
        }
        let arrT = this.getHiveTypeatt(val);
        for (let i in this.editinpStatus) {
          if (arrT.indexOf(i) > -1) {
            this.editinpStatus[i] = true
          }
          else this.editinpStatus[i] = false;
        }
      },
      cgFRule (val) {
        if (val == 'Custom') this.editinpStatus.ruleCode = true;
        else this.editinpStatus.ruleCode = false;
      },
      getEditinpShow () {
        return {
          hdfs: ["policy_name", "hdfs_dirs", "isaudit", "enabled", "isrecursion", "dialogFormVisible", "permissions", "policy_desc"],
          yarn: ["policy_name", "queue", "isaudit", "enabled", "isrecursion", "policy_desc", "permissions"],
          hive: this.getHiveTypeatt(this.form.policy_type || '普通策略'),
          hbase: ["policy_name", "hbaseTables", "column_family", "columns", "enabled", "include", "isaudit", "policy_desc", "permissions"],
          kafka: ["policy_name", "topic", "enabled", "isaudit", "ip", "policy_desc", "permissions"],
        }
      },
      updateEditInpStatus () {
        let type = this.ptype;
        let arr = this.getEditinpShow()[type];
        for (let key in this.editinpStatus) {
          if (arr.indexOf(key) > -1) this.editinpStatus[key] = true;
          else this.editinpStatus[key] = false;
        }
        if (this.editinpStatus.rule) this.cgFRule(this.form.rule)
        if (this.editinpStatus.udfSel) this.cgUdfSel(this.form.udfSel)

      },
      updateOptions () {
        let d = {
          hdfs: [{
            label: 'read',
            value: 'read'
          }, {
            label: 'write',
            value: 'write'
          }, {
            label: 'execute',
            value: 'execute'
          }],
          yarn: [{
            label: 'submit-app',
            value: 'submit-app'
          }, {
            label: 'admin-queue',
            value: 'admin-queue'
          }],
          hive: [{
            label: 'select',
            value: 'select'
          }, {
            label: 'update',
            value: 'update'
          }, {
            label: 'create',
            value: 'create'
          }, {
            label: 'drop',
            value: 'drop'
          }, {
            label: 'index',
            value: 'index'
          }, {
            label: 'lock',
            value: 'lock'
          }, {
            label: 'alter',
            value: 'alter'
          }, {
            label: 'all',
            value: 'all'
          }],
          hbase: [{
            label: 'read',
            value: 'read'
          }, {
            label: 'create',
            value: 'create'
          }, {
            label: 'admin',
            value: 'admin'
          }, {
            label: 'write',
            value: 'write'
          }],
          kafka: [{
            label: 'publish',
            value: 'publish'
          }, {
            label: 'create',
            value: 'create'
          }, {
            label: 'consume',
            value: 'consume'
          }, {
            label: 'configure',
            value: 'configure'
          }, {
            label: 'describe',
            value: 'describe'
          }, {
            label: 'delete',
            value: 'delete'
          }, {
            label: 'kafka_admin',
            value: 'kafka_admin'
          }]
        };
        this.options = d[this.ptype] || [];
      },
      form2req(){
        let form = JSON.parse(JSON.stringify(this.form));
//        if (form.permissions) form.acls = form.permissions.toString();
        if (form.permissions) form.acls = form.permissions;
        if (form.database) form.data_base = form.database.toString();
        form.enabled = form.enabled ? '1' : '0';
        form.isrecursion = form.isrecursion ? '1' : '0';
        form.include = form.include ? '1' : '0';
        form.isaudit = form.isaudit ? '1' : '0';
        switch (form.policy_type) {
          case '普通策略':
            form.policy_type = 0;
            break;
          case '模糊化策略':
            form.policy_type = 1;
            break;
          case '行过滤策略':
            form.policy_type = 2;
            break;
          default:
            form.policy_type = 0;
            break;
        }
        switch (this.ptype) {
          case "hdfs":
            break;
          case "yarn":
            break;
          case "hive":
            if (form.hiveTables) form.tables = form.hiveTables.toString();
            if (form.rule) form.data_mask_type = form.rule;
            if (form.ruleCode) form.value_expr = form.ruleCode;
            if (form.udfSel == "table") form.udf = void 0;
            break;
          case "hbase":
            if (form.hbaseTables) form.tables = form.hbaseTables.toString();
            if (!form.columns) {
              form.columns = '12';
            }
            break;
          case "kafka":
            if (form.topic) form.topic = form.topic.toString();
            break;
          default:
            break;
        }
        return form
      },
      res2form () {
        //获取当前选中的记录
        let form = JSON.parse(JSON.stringify(this.multipleSelection[0]));
        switch (form.policy_type) {
          case 0:
            form.policy_type = '普通策略';
            break;
          case 1:
            form.policy_type = '模糊化策略';
            break;
          case 2:
            form.policy_type = '行过滤策略';
            break;
          default:
            form.policy_type = '普通策略';
            break;
        }
        if (form.acls) form.permissions = form.acls.split(',');
        if (form.data_base) form.database = form.data_base.split(',');
        form.enabled = form.enabled == '1' ? true : false;
        form.isrecursion = form.isrecursion == '1' ? true : false;
        form.include = form.include == '1' ? true : false;
        form.isaudit = form.isaudit == '1' ? true : false;
        switch (this.ptype) {
          case "hdfs":
            break;
          case "yarn":
            break;
          case "hive":
            if (form.tables) form.hiveTables = form.tables.split(',');
            else form.hiveTables = []
            if (form.data_mask_type) form.rule = form.data_mask_type;
            if (form.value_expr) form.ruleCode = form.value_expr;
            if (form.udf) {
              form.udfSel = 'udf';
            }else  form.udfSel = 'table';
            break;
          case "hbase":
            if (form.tables) form.hbaseTables = form.tables.split(',');
            if (!form.columns) {
              form.columns = '12';
            }
            break;
          case "kafka":
            if (form.topic) form.topic = form.topic.split(',');

            break;
          default:
            break;
        }
        this.form = form
      },
      getFormDefault(){
        //清空form表单
        this.form = {
          udfSel: "table",
          udf: "",
          priv_data_serv_id: "",
          role_id: "",
          tenant_id: "",
          priv_policy_id: '',
          policy_type: '普通策略',
          policy_name: '',
          hdfs_dirs: '',
          queue: '',
          topic: [],
          ip: '',
          tables: '',
          hiveTables: [],
          hbaseTables: [],
          database: [],
          rule: '',
          column_family: '',
          columns: '',
          filter_expr: '',
          include: true,
          enabled: true, //是否启用
          isaudit: true,
          isrecursion: true,
          permissions: [],
          acls: '',
          topicList: [], //kafka列表
          policy_desc: '',
        };
      },
      handleAdd () {
        this.editinpStatus.priv_policy_id = false;
        this.disabled = false;
        this.formTitle = '创建';
        this.dialogFormVisible = true;

        if (this.ptype == 'hive') {
          this.getHiveDataBase();
        }
        if (this.ptype == 'hbase') {
          this.getHabseTableList();
        }
        if (this.ptype == 'kafka') {
          this.getKafkaTopicsHttp();
        }

        this.rules.policy_name = [
          {required: true, message: '请输入策略名称', trigger: 'blur'},
          {validator: util.validateString, trigger: 'blur'},
          {validator: this.validatePolicyName, trigger: 'blur'}
        ]
        this.getFormDefault();
        this.form.role_id = this.privdatas.role_id;
        this.form.tenant_id = this.privdatas.tenant_id;
        //修改字段
        this.updateEditInpStatus();
      },
      handleUpdate () {
        this.editinpStatus.priv_policy_id = true;
        this.disabled = true;
        this.formTitle = "编辑";
        this.dialogFormVisible = true;

        this.rules.policy_name = [
          {required: true, message: '请输入策略名称', trigger: 'blur'},
          {validator: util.validateString, trigger: 'blur'},
        ]
        this.res2form()
        //修改字段
        this.updateEditInpStatus();
      },
      handleDelete () {
        let arr = [];
        this.multipleSelection.map(item => {
          arr.push({
            "priv_policy_acl_id": item.priv_policy_acl_id,
            "priv_policy_id": item.priv_policy_id,
          })
        });
        if (arr.length == 0) {
          this.$message({
            message: '请至少选择一条记录！',
            type: 'warning'
          });
          return false;
        }
        this.$confirm('确认删除吗？', '提示', {type: 'info'})
          .then(() => {
            dao[this.deleteFun](arr)
              .then(res => {
                if (res.FX.err) return false;
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.getTableTitle();
              }, res => {
              })
          })
          .catch(() => {
          })
      },
      getTableTitle () {
        let privdatas = this.privdatas;
        let param = {
          role_id: privdatas.role_id,
          tenant_id: privdatas.tenant_id,
          policy_name: this.formInline.cOpts[0].val,
          start_index: this.pageParm.currentPage,
          page_count: this.pageParm.page_size
        };
        //查询
        let daofunc = 'get' + this.ptype.substring(0, 1).toUpperCase() + this.ptype.substring(1) + "Policy";
        dao[daofunc](param).then((response) => {
          if (response.FX.err) return false;
          let pageRes = response.body;
          if (typeof pageRes.results == 'object') {
            if (this.ptype == 'hive') {
              pageRes.results = pageRes.results.map(item => {
                let t = item.policy_type
                item.policy_type_name = (t == 0) ? '普通策略' : (t == 1 ? '模糊化策略' : '行过滤策略');
                return item;
              })
            }
            this.tableData = pageRes.results;
          }
          this.pageParm.count = parseInt(pageRes.count);
        }, (response) => {
        });
      },
      updateButStatus(val){
        if (val.length == 1) {
          this.butStatus.update = false;
          this.butStatus.rm = false;
        } else if (val.length == 0) {
          this.butStatus.update = true;
          this.butStatus.rm = true;
        } else {
          this.butStatus.update = true;
          this.butStatus.rm = false;
        }
      },
      handleSelectionChange (val) {
        this.multipleSelection = val
        this.updateButStatus(val)
      },
      handleSizeChange (val) {
        this.pageParm.page_size = val;
        this.getTableTitle();
      },
      handleCurrentChange (val) {
        this.pageParm.currentPage = val;
        this.getTableTitle();
      },
      editSubmit() {
        //校验
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {
              type: 'info'
            }).then(() => {
              this.btnEditText = '提交中';
              this.editLoading = true;

              let form = this.form2req();
              form.acls = form.acls.toString() || '';
              let fun = (this.form.priv_policy_id == "") ? this.addFun : this.updateFun;
              dao[fun](form).then(res => {
                this.btnEditText = '提 交';
                this.editLoading = false;
                this.dialogFormVisible = false;
                if (res.FX.err) return false;
                this.$message({
                  type: 'success',
                  message: '提交成功!'
                });
                //刷新列表
                this.getTableTitle();
              }).catch(res => {
                this.btnEditText = '提 交';
                this.editLoading = false;
                this.dialogFormVisible = false;
              });
            }).catch(() => {
              this.$message({
                message: '已经取消'
              });
            });
          }
        });
      },
      validatePolicyName (rule, value, callback) {
        //验证策略名称是否重复
        if (!value) {
          callback()
          return false
        } else {
          dao.judgePolicyName({
            "policy_name": this.form.policy_name,
            "method_type": this.ptype,
            role_id: this.form.role_id,
            tenant_id: this.form.tenant_id,
          }).then((response) => {
            if (!response.body.result) {
              callback(new Error('策略名重复!'));
            }
            callback()
          })
        }
      },
      pageInit () {
        this.getFormDefault()
        switch (this.ptype) {
          case "hdfs":
            this.addFun = 'addHdfsPolicy';
            this.updateFun = 'updateHdfsPolicy';
            this.deleteFun = 'deleteHdfsPolicy';
            this.tableTile = [
              {
                key: 'policy_name',
                name: '策略名'
              }, {
                key: 'hdfs_dirs',
                name: 'HDFS路径'
              }, {
                key: 'acls',
                name: '权限'
              }];

            break;
          case "yarn":
            this.addFun = 'addYarnPolicy';
            this.updateFun = 'updateYarnPolicy';
            this.deleteFun = 'deleteYarnPolicy';
            this.tableTile = [{
              key: 'policy_name',
              name: '策略名'
            }, {
              key: 'queue',
              name: 'YARN队列'
            }, {
              key: 'acls',
              name: '权限'
            }];
            break;
          case "hive":
            this.addFun = 'addHivePolicy';
            this.updateFun = 'updateHivePolicy';
            this.deleteFun = 'deleteHivePolicy';
            this.tableTile = [{
              key: 'policy_name',
              name: '策略名'
            }, {
              key: 'tables',
              name: 'HIVE表'
            }, {
              key: 'policy_type_name',
              name: '类型',

            }, {
              key: 'acls',
              name: '权限/策略'
            }];
            break;
          case "hbase":
            this.addFun = 'addHbasePolicy';
            this.updateFun = 'updateHbasePolicy';
            this.deleteFun = 'deleteHbasePolicy';
            this.tableTile = [{
              key: 'policy_name',
              name: '策略名'
            }, {
              key: 'tables',
              name: 'HBASE表'
            }, {
              key: 'acls',
              name: '权限'
            }];
            break;
          case "kafka":
            this.addFun = 'addKafkaPolicy';
            this.updateFun = 'updateKafkaPolicy';
            this.deleteFun = 'deleteKafkaPolicy';
            this.tableTile = [{
              key: 'policy_name',
              name: '策略名'
            }, {
              key: 'topic',
              name: 'Topic'
            }, {
              key: 'acls',
              name: '权限'
            }];
            break;
          default:
            break;
        }

        this.form.role_id = this.privdatas.role_id;
        this.form.tenant_id = this.privdatas.tenant_id;

        this.updateOptions();
        //this.getHabseTableList();
        this.getHiveTableList();
        this.getHiveDataBase();
        this.getTableTitle();
        this.getKafkaTopicsHttp();
      },
      getHabseTableList () {
        let tenant_id = util.fetch('page212_tenement')
        dao.listNameSpaceFromLocal({"tenant_id": tenant_id}).then(res => {

          let tableList = [];
          (res.body.results || []).map(re => {
            let name_space_table = re.namespace + ":*";
            tableList.push({label: name_space_table, value: name_space_table});
          });
          this.hbaseTableNameopts = tableList;
        });
      },
      getHiveDataBase () {
        let tenant_id = util.fetch('page212_tenement')
        dao.getHiveDB({'tenant_id': tenant_id}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            return false;
          }
          let databaseList = res.body.results || [];
          let dbList = [];
          databaseList.map(item => {
            dbList.push({label: item.hive_database_name, value: item.hive_database_name});
          });
          this.databaseNameopts = dbList;
        });
      },
      getHiveTableList () {
        if (this.type != 'hive') return false
        let hive_database_name = this.form.database;
        if ((hive_database_name == null || hive_database_name === "")
          && this.databaseNameopts != null && this.databaseNameopts.length > 0) {
          hive_database_name = this.databaseNameopts[0].value;
        }
        dao.getTablesListNoPage({"hive_database_names": hive_database_name}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            return false;
          }
          let tableList = res.body.tenant_hive || [];
          let hiveTableList = [];
          tableList.map(item => {
            (hiveTableList.indexOf(item.table) == -1) ? hiveTableList.push(item.table) : void 0;
          });
          hiveTableList = hiveTableList.map(item => {
            return {
              label: item,
              value: item
            }
          });
          this.hiveTableNameopts = hiveTableList;
        });
      },
      changeDb (str) {
        if (this.type != 'hive') return false
        this.getHiveTableList();

      },
      changeStates (e) {

        if (!e) {
          return false
        }
        function hdfsUpdate(arg) {
          dao.updateHdfsPolicy(arg).then((response) => {
            util.callbackTips({"retCode": response.body.retCode});
          })
        };
        function yarnUpdate(arg) {
          dao.updateYarnPolicy(arg).then((response) => {
            util.callbackTips(response.body.retCode);
          })
        };
        function hiveUpdate(arg) {
          dao.updateHivePolicy(arg).then((response) => {
            util.callbackTips(response.body.retCode);
          })
        };
        function hbaseUpdate(arg) {
          dao.updateHbasePolicy(arg).then((response) => {
            util.callbackTips(response.body.retCode);
          })
        };
        function kafkaUpdate(arg) {
          dao.updateKafkaPolicy(arg).then((response) => {
            util.callbackTips(response.body.retCode);
          })
        };

        let selectow = e;
        for (let k in selectow) {
          this.form[k] = selectow[k];
        }
        let arg = this.form;
        let title = "";
        if (arg.enabled == 0) {
          arg.enabled = false;
          title = "停止"
        } else if (arg.enabled == 1) {
          arg.enabled = true;
          title = "启动"
        }

        this.$confirm(`是否${title}该任务, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          switch (this.ptype) {
            case "hdfs":
              hdfsUpdate(arg);
              break;
            case "yarn":
              yarnUpdate(arg);
              break;
            case "hive":
              hbaseUpdate(arg);
              break;
            case  "hbase":
              hbaseUpdate(arg);
              break;
            case "kafka":
              kafkaUpdate(arg);
              break;
          }
          this.getTableTitle();
        })

      },
      getQueueOpts () {
        let tenant_id = util.fetch('page212_tenement')
        dao.getQueueByTennatId({'tenant_id': tenant_id}).then(res => {
          if (res.FX.err) {
            return false
          }
          this.queueOpts = res.body.queueList || [];
          this.pageInit();
        })
      },
      reSubmit (row) {
        dao[this.updateFun](row).then(res => {
          if (res.Fx.err) return false;
          this.getTableTitle()
        })
      },
      getKafkaTopicsHttp () { //获取kafka topics列表
        let tenant_id = util.fetch('page212_tenement')
        dao.getKafkaTopics({"tenant_id": tenant_id}).then(response => {
          if (response.body.retCode != 200 || response.status != 200) {
            return false
          }
          let list = response.body.results || [];
          this.topicList = list || [];
        })
      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialogFormVisible = false;
      },
      cgUdfSel(val){
        if (val == 'udf') {
          this.editinpStatus.udf = true;
          this.editinpStatus.hiveTables = false;
          this.editinpStatus.columns = false;
        } else {
          this.editinpStatus.udf = false;
          this.editinpStatus.hiveTables = true;
          this.editinpStatus.columns = true;
        }
      }
    },
    mounted () {
      this.pageInit();
    }
  }
</script>

<style scoped>
  .toolbar .el-form-item {
    margin-bottom: 10px;
  }

  .toolbar {
    background: #fff;
    padding: 10px 10px 0px 10px;
  }

  .el-select {
    width: 100%;
  }

  span.redTips {
    color: #ff4949;
  }

  span.greenTips {
    color: #13ce66;
  }
</style>